#include "Common.h"

std::vector<Texture2D*> MyTexture2D::TextureVector;
std::vector<MyTexture2D> MyTexture2D::tex[MyTexture2D::MaxType];

int MyTexture2D::addImage(const char* path, Type type, int index, int offsetX, int offsetY, bool load)
{
	//int type_i = type;
	tex[type][index]._offset = Point(offsetX, -offsetY);
	tex[type][index]._load = load;
	tex[type][index]._index = index;
	tex[type][index]._s = path;
	tex[type][index]._type = type;

	Texture2D* t = nullptr;
	if (load)
	{
		char s[255];
		sprintf(s, "%s/%d.png", path, index);
		if (FileUtils::getInstance()->isFileExist(s))
		{

			t = Director::getInstance()->getTextureCache()->addImage(s);
			//tex[0][index].addImage(s);
		}
		else
		{
			sprintf(s, "%s/%d_0.png", path, index);
			if (FileUtils::getInstance()->isFileExist(s))
			{
				t = Director::getInstance()->getTextureCache()->addImage(s);
				//tex[0][index].addImage(s);
			}
		}
	}
	tex[type][index]._texture = t;
	tex[type][index]._first = &tex[type][index];
	if (t)
	{
		tex[type][index]._firstInVector = TextureVector.size();
		TextureVector.push_back(t);
	}

	return 0;
}

void MyTexture2D::setToSprite(Sprite* s, Point p)
{
	auto t = this;
	if (t&&!t->_load)
	{
		addImage(t->_s, t->_type, t->_index, t->getOffset().x, -t->getOffset().y, true);
	}
	if (t&&t->getTexture())
	{
		s->setPosition(p - t->getOffset());
		s->setVisible(true);
		s->setTexture(t->getTexture());
		auto r = Rect::ZERO;
		r.size = t->getTexture()->getContentSize();
		s->setTextureRect(r);
	}
}

void CommonScene::ReadFile(const char* tfile, void* data, int length)
{
	std::string s1 = FileUtils::getInstance()->fullPathForFilename(tfile);
	FILE* fp = fopen(s1.c_str(), "rb");
	fread(data, 1, length, fp);
	fclose(fp);
}

Point CommonScene::GetPositionOnScreen(int x, int y, int CenterX, int CenterY)
{
	Point p;
	p.x = -(x - CenterX) * 18 + (y - CenterY) * 18 + Center_X;
	p.y = -((x - CenterX) * 9 + (y - CenterY) * 9 - Center_Y);
	return p;
}
